package com.example.dingtalkwebproject.utils;

import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * 钉钉AccessToken工具类
 */
public class DingTalkTokenUtil {

    // 应用凭证
    private static final String APP_KEY = "ding5qfapkdl1d7xvj9f";
    private static final String APP_SECRET = "61ae-qWMZsgF3nISqJ6S4EfaMmC573Du0tgsoEkL8SenxQJhxXp-B2NEDajVTKbX";

    // Token缓存
    private static String cachedAccessToken;
    private static long tokenExpireTime;

    // 客户端实例
    private static Client dingTalkClient;

    /**
     * 初始化钉钉客户端
     */
    private static synchronized Client getClient() throws Exception {
        if (dingTalkClient == null) {
            Config config = new Config();
            config.protocol  = "https";
            config.regionId  = "central";
            dingTalkClient = new Client(config);
        }
        return dingTalkClient;
    }

    /**
     * 获取AccessToken (带缓存机制)
     */
    public static String getAccessToken() throws Exception {
        // 如果缓存中有未过期的Token，直接返回
        if (!StringUtils.isEmpty(cachedAccessToken)  && System.currentTimeMillis()  < tokenExpireTime) {
            return cachedAccessToken;
        }

        try {
            Client client = getClient();
            GetAccessTokenRequest request = new GetAccessTokenRequest()
                    .setAppKey(APP_KEY)
                    .setAppSecret(APP_SECRET);

            GetAccessTokenResponse response = client.getAccessToken(request);

            // 更新缓存
            cachedAccessToken = response.getBody().getAccessToken();
            // 提前5分钟过期，避免临界点问题
            tokenExpireTime = System.currentTimeMillis()  + TimeUnit.SECONDS.toMillis(response.getBody().getExpireIn())  - TimeUnit.MINUTES.toMillis(5);

            return cachedAccessToken;

        } catch (TeaException e) {
            // 处理阿里云SDK特定异常
            throw new RuntimeException("获取钉钉AccessToken失败: " + e.code  + " - " + e.message,  e);
        } catch (Exception e) {
            // 处理其他异常
            throw new RuntimeException("获取钉钉AccessToken发生未知错误", e);
        }
    }

    /**
     * 清除缓存的Token (强制下次获取新Token)
     */
    public static void clearTokenCache() {
        cachedAccessToken = null;
        tokenExpireTime = 0;
    }

    /**
     * 测试方法
     */
    public static void main(String[] args) {
        try {
            String accessToken = getAccessToken();
            System.out.println(" 获取AccessToken成功: " + accessToken);

            // 测试缓存
            String cachedToken = getAccessToken();
            System.out.println(" 从缓存获取AccessToken: " + cachedToken);

        } catch (Exception e) {
            System.err.println(" 获取AccessToken失败:");
            e.printStackTrace();
        }
    }
}